package com.java.simple.smallspring.beans.factory;

import com.java.simple.smallspring.beans.BeansException;
import com.java.simple.smallspring.beans.PropertyValue;
import com.java.simple.smallspring.beans.PropertyValues;
import com.java.simple.smallspring.beans.factory.config.BeanDefinition;
import com.java.simple.smallspring.beans.factory.config.BeanFactoryPostProcessor;
import com.java.simple.smallspring.core.io.DefaultResourceLoader;
import com.java.simple.smallspring.core.io.Resource;
import com.java.simple.smallspring.util.StringValueResolver;
import java.io.IOException;
import java.util.Properties;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

/**
 * @author zhoujunlin
 * @date 2022年09月27日 16:39
 * @desc
 */
@Setter
public class PropertyPlaceholderConfigurer implements BeanFactoryPostProcessor {

    /**
     * default placeholder prefix for @value
     */
    public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";
    /**
     * default placeholder suffix for @value
     */
    public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";

    private String location;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        try {
            // 加载属性文件
            DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource(location);
            //占位符替换属性值
            Properties properties = new Properties();
            properties.load(resource.getInputStream());
            String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
            for (String beanName : beanDefinitionNames) {
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                PropertyValues propertyValues = beanDefinition.getPropertyValues();
                for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                    Object value = propertyValue.getValue();
                    if (!(value instanceof String)) {
                        continue;
                    }
                    value = resolvePlaceholder((String) value, properties);
                    propertyValues.addPropertyValue(new PropertyValue(propertyValue.getName(), value));
                }
            }
            // 向容器中添加字符串解析器  供解析@Value注解使用
            PlaceholderResolvingStringValueResolver valueResolver = new PlaceholderResolvingStringValueResolver(properties);
            beanFactory.addEmbeddedValueResolver(valueResolver);
        } catch (IOException e) {
            throw new BeansException("Could not load properties", e);
        }
    }

    private String resolvePlaceholder(String value, Properties properties) {
        StringBuilder strBuilder = new StringBuilder(value);
        int startIdx = value.indexOf(DEFAULT_PLACEHOLDER_PREFIX);
        int stopIdx = value.indexOf(DEFAULT_PLACEHOLDER_SUFFIX);
        if (startIdx != -1 && stopIdx != -1 && startIdx < stopIdx) {
            String propKey = value.substring(startIdx + 2, stopIdx);
            String propVal = properties.getProperty(propKey);
            strBuilder.replace(startIdx, stopIdx + 1, propVal);
        }
        return strBuilder.toString();
    }

    @RequiredArgsConstructor
    private class PlaceholderResolvingStringValueResolver implements StringValueResolver {

        private final Properties properties;

        @Override
        public String resolveStringValue(String strVal) {
            return PropertyPlaceholderConfigurer.this.resolvePlaceholder(strVal, properties);
        }
    }

}
